﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using LLoger;
using System.Linq;

namespace LimitatorInterfaces
{
    public class ConfigReader
    {
        private readonly Configuration _config;
        protected readonly ILogWriter LogWriter;

        public ConfigReader(string configFileName, ILogWriter logWriter)
        {
            if (string.IsNullOrWhiteSpace(configFileName))
                throw new ArgumentException("Не задан файл конфигурации", "configFileName");

            string path = configFileName;

            if (!File.Exists(path))
                throw new FileNotFoundException("Файл конфигурации не найден: " + path);


            ExeConfigurationFileMap mapCfg = new ExeConfigurationFileMap();
            mapCfg.ExeConfigFilename = path;

            _config = ConfigurationManager.OpenMappedExeConfiguration(mapCfg,ConfigurationUserLevel.None); //OpenExeConfiguration(configFileName);
            LogWriter = logWriter ?? new DummyLog();
        }

        public string GetSettingValue(string key)
        {
            try
            {
                var obj = _config.AppSettings.Settings[key].Value;
                return obj;
            }
            catch (Exception ex)
            {
                LogWriter.WriteLine(ex);
                throw new Exception(ex.Message, ex);
            }
        }

        public KeyValuePair<string, string>[] GetStartWithSettingValues(string key)
        {
            try
            {
                var config = _config.AppSettings.Settings;

                if (config == null || config.Count == 0)
                    return null;

                var keys = config.AllKeys.Where(v => v.StartsWith(key)).ToArray();

                var keysCnt = keys.Count();

                if (keysCnt == 0)
                    return null;

                if (keysCnt == 1)
                    return new[] { new KeyValuePair<string, string>(config[keys[0]].Key, config[keys[0]].Value) };

                var res = from k in keys
                          select config[k];

                return res.Select(v => new KeyValuePair<string, string>(v.Key, v.Value)).ToArray();
            }
            catch (Exception ex)
            {
                LogWriter.WriteLine(ex);
                throw new Exception(ex.Message, ex);
            }
        }
    }
}